package com.c.business.interceptor;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.c.business.util.RedisUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

@Component
public class SessionInterceptor implements HandlerInterceptor {
    @Autowired
    private RedisUtils redisUtils;

    //验证码过期  30分钟
    private final static int EXPIRE = 1800;

    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
        String servletPath = httpServletRequest.getServletPath();
        System.out.println(servletPath);

        String[] NoFilter = new String[] { "api", "application", "carinsurefront", "WeiXin", "uploadFile", "download",
                "login", "H5", "CarH5","yunmai",".jpg","downLoadOffer","upLoadPremium","downLoadExcel","downLoadCommentOffer",
                "downLoadExcel","ExportOrderList"};
        for (String string : NoFilter) {
            if (servletPath.contains(string))
                return true;
        }

        String token = httpServletRequest.getHeader("token");
        if (StrUtil.isBlank(token)) {
            httpServletResponse.setCharacterEncoding("UTF-8");
            httpServletResponse.setContentType("application/json; charset=utf-8");
            JSONObject json = new JSONObject();
            json.put("code", 300);
            json.put("message", "请重新登陆");
            PrintWriter out = null;
            out = httpServletResponse.getWriter();
            out.append(json.toString());
            return false;
        } else {
            Object object = redisUtils.get(token);
            if(object.equals("null"))
            {
                httpServletResponse.setCharacterEncoding("UTF-8");
                httpServletResponse.setContentType("application/json; charset=utf-8");
                JSONObject json = new JSONObject();
                json.put("code", 300);
                json.put("msg", "请重新登陆");
                PrintWriter out = null;
                out = httpServletResponse.getWriter();
                out.append(json.toString());
                return false;
            }
            redisUtils.set(token, object, EXPIRE);
            return true;
        }
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}
